#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "inetAddr.hpp"

using namespace LogModule;

const std::string defaultDictPath = "./dictionary.txt";
const std::string sep = ": ";

class Dict
{
public:
    Dict(const std::string dict_path = defaultDictPath)
        :_dict_path(dict_path)
    {}

    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "open dictionary error";
            return false;
        }
        std::string line;
        while(std::getline(in, line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "dict: " << line << " error";
                continue;
            }
            std::string English = line.substr(0, pos);
            std::string Chinese = line.substr(pos + sep.size());
            if(English.empty() || Chinese.empty())
            {
                LOG(LogLevel::WARNING) << "dict: " << line << " error";
                continue;
            }
            _dict[English] = Chinese;
            LOG(LogLevel::DEBUG) << "load " << line << " success";
        }
        in.close();
        return true;
    }

    std::string Translate(const std::string& word, InetAddr& client)
    {
        LOG(LogLevel::INFO) << client.Ip() << ":" << client.Port() << " ask for translate";
        //LOG(LogLevel::DEBUG) << "translate start";
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            LOG(LogLevel::INFO) << word << "->None"; 
            return "None";
        }
        LOG(LogLevel::INFO) << word << "->" << iter->second; 
        return iter->second;
    }
    ~Dict(){}
private:
    std::string _dict_path;// 路径加文件名
    std::unordered_map<std::string, std::string> _dict;
};